from flask_restful import Resource, fields, marshal_with, reqparse
from flask import jsonify
from .models import *


# 类视图  CBV
# 视图函数  FBV

class HelloResource(Resource):
    def get(self):
        return jsonify({"data": "get请求"})
    def post(self):
        return jsonify({"data":'post请求'})

ret_fields = {
    'status': fields.Integer,
    'msg': fields.String,
    # 'data': fields.String
    'like': fields.String(default='喜洋洋'),
    'like2': fields.String()
}
class userResouce(Resource):
    @marshal_with(ret_fields)
    def get(self):
        return {
            'status': 1,
            'msg': 'ok',
            'data': 'lzr python'
        }


user_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'age': fields.Integer,
    'sex': fields.Integer,
    'salary': fields.Integer,
}
ret_fields2 = {
    'status': fields.Integer,
    'msg': fields.String,
    'data': fields.Nested(user_fields)
}
class User2Resource(Resource):
    @marshal_with(ret_fields2)
    def get(self):
        user = User.query.get(1)
        return {
            'status': 1,
            'msg': 'ok',
            'data': user
        }


ret_fields3 = {
    'status': fields.Integer,
    'msg': fields.String,
    'data': fields.List(fields.Nested(user_fields))
}

class User3Resource(Resource):
    @marshal_with(ret_fields3)
    def get(self):
        users = User.query.all()
        return {
            'status': 1,
            'msg': 'ok',
            'data': users
        }


parser = reqparse.RequestParser()
parser.add_argument('name', type=str)
parser.add_argument('age', type=int, required=True, help='age是必须的')
parser.add_argument('key', type=str, location='cookies')
class Users4(Resource):
    def get(self):
        parse = parser.parse_args()
        name = parse.get('name')
        age = parse.get('age')
        key = parse.get('key')
        return {
            name, age, key
        }

